package com.lianzai.shop.controller;

import com.lianzai.shop.model.Shop;
import com.lianzai.shop.service.ShopService;
import com.lianzai.common.controller.BaseController;
import com.lianzai.common.utils.PageUtils;
import com.lianzai.common.utils.Query;
import com.lianzai.common.utils.R;
import com.lianzai.ticket.model.Ticket;
import com.lianzai.util.FileUtil;
import com.lianzai.util.TimeUtil;
import org.apache.commons.collections.map.HashedMap;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/shop")
public class ShopController extends BaseController {

    @Autowired
    ShopService shopService;

    @Value("${license.windows-path}")
    private String licenseWinPath;

    @Value("${license.linux-path}")
    private String licenseLinuxPath;

    @GetMapping()
    String ticket(Model model){
        List<Map<String, String>> industryList = shopService.queryIndustryList();
        model.addAttribute("industryList",industryList);
        return "shop/list";
    }

    @ResponseBody
    @GetMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params){
        //查询列表数据
        params.put("role","3");//只查询商户
        Query query = new Query(params);
        List<Shop> carInfoList = shopService.list(query);
        int total = shopService.count(query);
        PageUtils pageUtils = new PageUtils(carInfoList, total);
        return pageUtils;
    }

    @PostMapping( "/remove")
    @ResponseBody
    public R remove( Long id){
        //校验如果是审核通过状态则不能删除
        Map params = new HashedMap();
        params.put("shopId",id);
        /*List<Map> ticketShopList = ticketService.queryTicektShopUsedList(params);
        if(ticketShopList != null && ticketShopList.size() > 0){
            return R.error(110,"无法删除，有商户在用");
        }else{
            if(ticketService.remove(id)>0){
                return R.ok();
            }
        }*/
        if(shopService.remove(id)>0){
            shopService.removeLicense(id);
            return R.ok();
        }
        return R.error();
    }

    @GetMapping("/add")
    String add(){
        return "shop/add";
    }

    @GetMapping("/audit/{id}")
    String audit(@PathVariable("id") Long id,Model model){
        Shop shop = shopService.get(id);
        String licensePath = shop.getLicensePhotoPath();
        if(licensePath == null || "".equals(licensePath)){
            shop.setLicensePhotoPath("/img/m/nofound.jpg");
        }
        model.addAttribute("shop", shop);
        return "shop/audit";
    }

    @GetMapping("/edit/{id}")
    String edit(@PathVariable("id") Long id,Model model){
        Shop shop = shopService.get(id);
        String licensePath = shop.getLicensePhotoPath();
        model.addAttribute("licUrl",licensePath);
        if(licensePath == null || "".equals(licensePath)){
            model.addAttribute("licenseName", "");
            shop.setLicensePhotoPath("/img/m/nofound.jpg");
        }else{
            licensePath = licensePath.replaceAll("/","\\\\");
            String[] licPathArray = licensePath.split("\\\\");
            if(licPathArray.length==4){//暂定为三级
                model.addAttribute("licenseName", licPathArray[3]);
                shop.setLicensePhotoPath(shop.getLicensePhotoPath()+"?t="+TimeUtil.queryCurTime());
            }else{
                model.addAttribute("licenseName", "");
                shop.setLicensePhotoPath("/img/m/nofound.jpg");
            }

        }

        List<Map<String, String>> industryList = shopService.queryIndustryList();
        model.addAttribute("industryList",industryList);
        model.addAttribute("shop", shop);
        return "shop/edit";
    }

    @ResponseBody
    @PostMapping("/save")
    public R save( Shop shop){
        if(shopService.save(shop)>0){
            return R.ok();
        }
        return R.error();
    }

    /**
     * 文件上传
     * @param file
     * @param id
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/upload",method = RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file,
                     @RequestParam("id") Long id,
                     PrintWriter out,
                     HttpServletRequest request){
        JSONObject retJson = new JSONObject();
        try{
            String osName = System.getProperty("os.name");
            String licensePath = licenseLinuxPath;
            if(osName.contains("Windows") || osName.contains("windows")){
                licensePath = licenseWinPath;
            }
            retJson.put("upflag", "success");
            if(licensePath.startsWith("file:")){
                licensePath=licensePath.substring(5);
            }
            String licPath = licensePath+id;
            File licenseFolder = new File(licPath);
            if(!licenseFolder.exists()){
                licenseFolder.mkdir();
            }
            FileUtil.delFolderFiles(licPath);
            //将原有目录下的图片清除掉
            String logoName = FileUtil.getLogoName(file.getOriginalFilename());
            //String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //将文件拷贝到其目录下并重命名未license.xxx
            File logoFile=new File(licPath+File.separator + logoName);
            file.transferTo(logoFile);
            //更新license路径
            Shop shop = new Shop();
            shop.setId(id);
            shop.setLicensePhotoPath("/license/"+id+"/"+logoName);
            shopService.removeLicense(id);
            shopService.insertLicense(shop);
            //shopService.updateLicense(shop);
        }catch (Exception e){
            e.printStackTrace();
            retJson.put("upflag", "fail");
        }
        out.println(retJson.toString());
        return null;
    }

    @ResponseBody
    @RequestMapping(value="/update",method = RequestMethod.POST)
    public R update( Shop shop){
        if(shopService.update(shop)>0){
            return R.ok();
        }
        return R.error();
    }

    @ResponseBody
    @RequestMapping("/shenhe")
    public R shenhe( Shop shop){
        if(shopService.pass(shop)>0){
            return R.ok();
        }
        return R.error();
    }
}
